package com.yupi.springbootinit.mq;

import com.rabbitmq.client.*;

import java.util.Scanner;

public class DlxProducer {

    private static final String DEAD_EXCHANGE_NAME = "dlx";

    private static final String EXCHANGE_NAME = "direct2-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //创建死信交换机
            channel.exchangeDeclare(DEAD_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            //创建死信队列
            String queueName1 = "boss";
            channel.queueDeclare(queueName1, true, false, false, null);
            channel.queueBind(queueName1, DEAD_EXCHANGE_NAME, "boss");

            //创建第二个死信队列
            String queueName2 = "outsourcing";
            channel.queueDeclare(queueName2, true, false, false, null);
            channel.queueBind(queueName2, DEAD_EXCHANGE_NAME, "outsourcing");

            //消息的处理操作  监听boss的死信队列
            DeliverCallback bossDeliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                //拒绝消息
                channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
                System.out.println(" [boss] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
            };
            //监听outsourcing的死信队列
            DeliverCallback outsourcingDeliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                //拒绝消息
                channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
                System.out.println(" [outsourcing] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
            };

            channel.basicConsume(queueName1, false, bossDeliverCallback, consumerTag -> {});
            channel.basicConsume(queueName2, false, outsourcingDeliverCallback, consumerTag -> {});

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String userInput = scanner.nextLine();
                String[] strings = userInput.split(" ");
                if (strings.length < 1) {
                    continue;
                }
                String message = strings[0];
                String routingKey = strings[1];

                channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "'with routing:'" + routingKey + "'");
            }
        }
    }

}
